var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var schedule = require('node-schedule');
var fs = require('fs');
// var httpProxyMiddleware = require('http-proxy-middleware');
var proxyMiddleware = require('proxy-middleware');

function scheduleCronstyle() {
  schedule.scheduleJob('0 0 * * * *', function () {
    // 清理无用的任务文件
    console.log('检查是否有无用的任务:' + new Date());
    var path = "/tmp/";
    var files = fs.readdirSync(path);
    files.forEach(function (itm, index) {
      if (itm.length < 5 || itm.substring(itm.length - 4) != ".tar") {
        return;
      }
      var stat = fs.statSync(path + itm);
      if (stat.isDirectory()) {
      } else {
        if (new Date().getTime() - stat.mtime.getTime() >= 3600 * 1000) {
          fs.unlinkSync(path + itm);
          console.log('删除无用的任务结果:' + path + itm);
        }
      }
    });
    console.log('检查是否有无用的任务完成');
  });
}

scheduleCronstyle();

var route_index = require('./routes/index');
var route_upload = require('./routes/upload');
var route_uploadsingle = require('./routes/uploadsingle');
var route_uploadsome = require('./routes/uploadsome');
var route_download = require('./routes/download');
var route_search = require('./routes/search');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine("html",require("ejs").__express); // or   app.engine("html",require("ejs").renderFile);
// app.set('view engine', 'ejs');
app.set('view engine', 'html');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
// 静态资源的加载
app.use(express.static(path.join(__dirname, 'static')));

app.use(route_index);
app.use(route_upload);
app.use(route_uploadsingle);
app.use(route_uploadsome);
app.use(route_download);

// 反向代理
// 通过外部仓库提供的查询服务，获取匹配的包的信息
// searchArtifactByGav?_input_charset=utf-8&groupId=commons-io&repoId=central&artifactId=commons-io&version=1.1
// searchArtifactByWords?_input_charset=utf-8&queryTerm=flink&repoId=central
// app.use('/search/keyword', proxyMiddleware('https://pkg.go.dev/search'));
app.use(route_search);

// // catch 404 and forward to error handler
// app.use(function(req, res, next) {
//   var err = new Error('Not Found');
//   err.status = 404;
//   next(err);
// });

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});


module.exports = app;
